package com.steptime.jdbc;

import org.junit.Test;

import java.sql.*;

/**
 * 1、jdbc简单示例
 * 2、模拟SQL注入漏洞过程
 * 3、放置SQL注入漏洞
 */
public class JdbcDemo {
    /**
     * SQL注入漏洞 演示
     */
    @Test
    public void login(){
       // boolean sucess = validateUser("admin' or '1=1 ", "1111");
        //boolean sucess = validateUser("admin' -- ", "1111");
        boolean sucess = validateUser2("admin", "111");
        if (sucess) {
            System.out.println("登录成功!");
        }else {
            System.err.println("登陆失败!");
        }
    }

    /**
     * 通过Statement对象执行sql
     * @param username
     * @param pwd
     * @return
     */
    public static boolean validateUser(String username,String pwd) {
        boolean valid = false;
        try {
            Connection conn = JdbcUtil.getConnection();
            Statement statement = conn.createStatement();
            String sql = "select  * from emp where username ='" + username + "' and pwd ='" + pwd + "'";
            ResultSet resultSet = statement.executeQuery(sql);
            if (resultSet.next()) {
                valid = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return valid;
    }


    /**
     * 通过Statement对象执行sql
     * @param username
     * @param pwd
     * @return
     */
    public static boolean validateUser2(String username,String pwd) {
        boolean valid = false;
        try {
            Connection conn = JdbcUtil.getConnection();

            String sql = "select  * from emp where username = ? and pwd = ?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2,pwd);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                valid = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return valid;
    }
}
